<template>
  <div class="purchase-list-layout role-layout">
    <crumbList :navList="navList"></crumbList>
    <div class="purchase-content role-content">
      <div class="purchase-table role-table">
        <div class="purchase-item">
          <el-form ref="searchData" :model="searchData" class="clearfix">
            <el-form-item class="principalItem">
              <el-input v-model="searchData.name" placeholder="角色名称"></el-input>
            </el-form-item>
            <el-form-item class="itemButton">
              <el-button type="primary" @click="search">查询</el-button>
              <el-button type="primary" @click="reset">重置</el-button>
              <el-button type="primary" class="addItem" @click="addRoleDialog = true">新增角色</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="purchase-table-list">
          <el-table :data="tableData" border>
            <el-table-column :label="item.label" v-for="(item, index) in table" :key="index" :width="item.name==='orderNum'?64:''">
              <template scope="scope">
                <span v-if="item.name === 'name'">
                  <span v-show="!scope.row.edit" :title="scope.row[item.name]">{{ scope.row[item.name] }}</span>
                  <span v-show="scope.row.edit">
                    <el-input v-model="scope.row.name" placeholder="输入角色名称"></el-input>
                  </span>
                </span>

                <span v-else-if="item.name === 'orderNum'">
                  <span :title="scope.row[item.name]">{{ scope.$index + 1 }}</span>
                </span>

                <span v-else-if="item.name === 'description'">
                  <span v-show="!scope.row.edit" :title="scope.row[item.name]">{{ scope.row[item.name] }}</span>
                  <span v-show="scope.row.edit">
                    <el-input v-model="scope.row.description" placeholder="输入备注"></el-input>
                  </span>
                </span>

                <span v-else :title="scope.row[item.name]">{{ scope.row[item.name] }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="300">
              <template scope="scope">
                <el-button v-show='!scope.row.edit' type="primary" class="editBtn" @click='scope.row.edit = true' :disabled="scope.row.id === 1 ? true : false">修改</el-button>
                <el-button v-show='scope.row.edit' type="primary" class="editBtn" @click='handleUpdate(scope.$index, scope.row)'>完成</el-button>
                <el-button type="primary" class="accessoryBtn fourFontWid" @click="setRole(scope.$index, scope.row)" :disabled="scope.row.id === 1 ? true : false">设置权限</el-button>
                <el-button type="primary" class="deleteBtn" @click="remove(scope.$index, scope.row)" :disabled="scope.row.id === 1 ? true : false">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="block">
          <el-pagination layout="total, prev, pager, next, jumper"
                         @current-change="handleCurrentChange"
                         :current-page="page.pageNum"
                         :page-size="page.pageSize"
                         :total="page.total">
          </el-pagination>
        </div>
      </div>
    </div>
    <!--新增角色-->
    <el-dialog class="role-dialog" v-model="addRoleDialog" title="新增角色" @close="dialogFormClose('addRoleForm')" top="70px">
      <div>
        <el-form :model="addRoleForm" :rules="rules" ref="addRoleForm" label-width="20%" label-position="right">
          <el-form-item prop="name" label="角色名称">
            <el-input v-model="addRoleForm.name"></el-input>
          </el-form-item>
          <el-form-item prop="description" label="备注">
            <el-input v-model="addRoleForm.description"></el-input>
          </el-form-item>
          <div class="operationBtn">
            <el-button class="cancelBtn" @click="dialogFormClose('addRoleForm')">取消</el-button>
            <el-button class="nextBtn" @click="submitForm('addRoleForm')">提交</el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
    <!--角色权限设置-->
    <el-dialog class="role-dialog" v-model="setRoleDialog" title="设置权限" @close="dialogRoleClose" top="70px">
      <div>
        <div class="role-dialog-header">
          <el-tag type="primary">角色名称：{{dialogRoleName}}</el-tag>
        </div>
        <div class="role-dialog-body">
          <div class="role-dialog-check" v-for="(item,index) in setRoleData" :key="index">
            <el-checkbox v-model="item.checked" @change="handleCheckAllChange(index)" :disabled="item.disabled">{{ item.moduleName }}</el-checkbox>
            <el-checkbox-group v-model="item.checkVal">
              <el-checkbox v-for="check in item.moduleItems" :label="check.id" :key="check.moduleName" :disabled="item.checked === false ? true : false">{{ check.moduleName }}</el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
        <div class="operationBtn">
          <el-button class="cancelBtn" @click="dialogRoleClose">取消</el-button>
          <el-button class="nextBtn" @click="submitRoleData">提交</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import copyObject from '../../../utils/copyObject/copyObject'
  import ajax from '../../../utils/ajax/index'
  import crumbList from '../../common/crumbList.vue'
  import setRoleInfo from './js/setRoleInfo'
  import getRole from './js/getRole'
  import formatRoleData from './js/formatRoleData'
  import clearRoleInfo from './js/clearRoleInfo'

  export default {
    data () {
      return {
        navList: [
          {name: '设置', path: ''},
          {name: '角色管理', path: ''}
        ],
        searchData: {
          name: ''
        },
        tableData: [],
        table: [
          {label: '序号', name: 'orderNum'},
          {label: '角色名称', name: 'name'},
          {label: '备注', name: 'description'},
          {label: '创建时间', name: 'createTime', sortable: true}
        ],
        page: {
          pageNum: 1,
          pageSize: 10,
          total: 1,
          pages: 1
        },
        addRoleDialog: false,
        setRoleDialog: false,
        addRoleForm: {
          name: '',
          description: ''
        },
        rules: { // 新增表单规则
          name: [
            { required: true, message: '请输入角色名称', toggle: 'blur' },
            { min: 2, max: 25, message: '长度在2-25之间' }
          ],
          description: [
            { min: 2, max: 25, message: '长度在2-25之间' }
          ]
        },
        setRoleData: [],
        dialogRoleName: '',
        roleId: ''
      }
    },
    components: {crumbList},
    mounted () {
      this.result()
      this.setRoleInfo()
    },
    methods: {
      // 查询
      result (searchData) {
        let url = this.api.role.result
        let store = this.$store
        ajax.get(url, searchData || {}, store, true).then((res) => {
          let data = res.list
          let page = res.page
          this.page = copyObject(page)
          for (let i = 0; i < data.length; i++) {
            data[i].edit = false
            data[i].orderNum = i + 1
          }
          this.tableData = data
        })
      },
      search () { // 搜索
        this.searchData.pageNum = 1
        this.result(this.searchData)
      },
      // 重置
      reset () {
        this.searchData = {
          name: ''
        }
      },
      // 新增角色
      submitForm (formName) {
        let that = this
        let confirm = that.$confirm
        let store = that.$store
        let msg = that.$message
        let url = that.api.role.add

        that.$refs[formName].validate((valid) => {
          if (valid) { // 通过验证
            confirm('是否继续?', '提示', {confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'})
              .then(() => {
                that.addRoleForm.creater = sessionStorage.getItem('accountId') || 1
                store.dispatch('setLoading', true)
                ajax.post(url, that.addRoleForm, store).then((res) => {
                  let code = res.msg.code
                  let data = res.data
                  if (code === '20000') {
                    msg({type: 'success', message: '新增成功'})
                    that.tableData.unshift(data)
                    that.addRoleDialog = false
                  } else {
                    msg({type: 'error', message: res.msg.message})
                  }
                  store.dispatch('setLoading', false)
                }).catch((err) => {
                  if (err) throw err
                  store.dispatch('setLoading', false)
                  msg({type: 'error', message: '网络异常'})
                })
              }).catch(() => {})
          } else { // 未通过验证
            console.log('error')
          }
        })
      },
      // 修改
      handleUpdate (index, row) {
        row.edit = false
        let that = this
        let store = that.$store
        let msg = that.$message
        let url = that.api.role.update
        this.$mb('确认修改吗？', '提示').then(() => {
          row.modifier = sessionStorage.getItem('accountId')
          store.dispatch('setLoading', true)
          ajax.post(url, row, store).then((res) => {
            if (res.msg.code === '20000') {
              msg({type: 'success', message: '编辑成功'})
            } else {
              msg({type: 'error', message: res.msg.message})
            }
            store.dispatch('setLoading', false)
          }).catch((err) => {
            if (err) throw err
            store.dispatch('setLoading', false)
            msg({type: 'error', message: '网络异常'})
          })
        }).catch(() => {})
      },
      setRoleInfo () { // 写入权限列表
        let data = JSON.parse(sessionStorage.getItem('router'))
        this.setRoleData = setRoleInfo(data)
        console.log(this.setRoleData)
      },
      // 设置权限
      setRole (index, row) {
        let that = this
        let store = that.$store
        let msg = that.$message
        let url = that.api.role.getRole
        ajax.get(url, { id: row.id }, store, true).then((res) => {
          console.log(res)
          if (res.msg.code === '20000') {
            this.setRoleDialog = true
            this.dialogRoleName = row.name
            this.roleId = row.id
            getRole(res.data, this.setRoleData)
          } else {
            msg({type: 'error', message: '网络异常'})
          }
        }).catch((err) => {
          if (err) throw err
          msg({type: 'error', message: '网络异常'})
        })
      },
      submitRoleData () {
        let that = this
        let store = that.$store
        let msg = that.$message
        let url = that.api.role.updateRole
        let params = {}
        this.$mb('确认提交吗？', '提示').then(() => {
          store.dispatch('setLoading', true)
          params.roleId = that.roleId
          params.moduleId = formatRoleData(that.setRoleData)
          ajax.post(url, params, store).then((res) => {
            if (res.msg.code === '20000') {
              this.setRoleDialog = false
              msg({type: 'success', message: '权限设置成功'})
            } else {
              msg({type: 'error', message: res.msg.message})
            }
            store.dispatch('setLoading', false)
          }).catch((err) => {
            if (err) throw err
            store.dispatch('setLoading', false)
            msg({type: 'error', message: '网络异常'})
          })
        }).catch(() => {})
      },
      // 删除
      remove (index, row) {
        let that = this
        let store = that.$store
        let msg = that.$message
        let url = that.api.role.delete
        this.$mb('确认删除这个角色吗？', '提示').then(() => {
          store.dispatch('setLoading', true)
          ajax.post(url, { id: row.id }, store).then((res) => {
            if (res.msg.code === '20000') {
              that.tableData.splice(index, 1)
              msg({type: 'success', message: '删除成功'})
            } else {
              msg({type: 'error', message: res.msg.message})
            }
            store.dispatch('setLoading', false)
          }).catch((err) => {
            console.log(err)
            store.dispatch('setLoading', false)
            msg({type: 'error', message: '网络异常'})
          })
        }).catch(() => {})
      },
      handleCurrentChange (val) {
        this.searchData.pageNum = val
        this.result(this.searchData)
      },
      dialogFormClose (formName) { // 关闭新增弹窗
        this.$refs[formName].resetFields()
        this.addRoleDialog = false
      },
      dialogRoleClose () { // 关闭权限设置弹窗
        clearRoleInfo(this.setRoleData) // 调用清空权限选择数据函数
      }
    }
  }
</script>
